<template>
	<!-- 写一个大盒子，占满整个背景 -->
	<div class="register-background">
		<!-- 注册的窗口页面 -->
		<div class="register-box">
			<h1 class="login-title">用户注册</h1>
			<!-- 这是注册用的表单 -->
			<el-form ref="ruleFormRef" class="register-form demo-ruleForm" :model="registerForm" :rules="rules"
				status-icon label-width="120px">
				<!-- nickname，username，password，bio -->
				<!-- el-form-item标签中的一个单元 -->
				<el-form-item label="昵称:" prop="nickname">
					<el-input v-model="registerForm.nickname" placeholder="请输入或随机一个昵称">
						<template #append>
							<el-tooltip class="box-item" effect="dark" content="随机一个！" placement="right-start">
								<el-icon @click="getRandomName" style="">
									<Refresh />
								</el-icon>
							</el-tooltip>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="账户:" prop="username">
					<el-input v-model="registerForm.username" placeholder="请输入一个账户">
					</el-input>
				</el-form-item>
				<el-form-item label="密码1:" prop="password">
					<el-input v-model="registerForm.password" placeholder="请输入密码" show-password></el-input>
				</el-form-item>
				<el-form-item label="密码2:" prop="passwordAg">
					<el-input v-model="registerForm.passwordAg" placeholder="请重复输入密码" show-password></el-input>
				</el-form-item>
				<el-form-item label="个性签名:">
					<el-input v-model="registerForm.bio" maxlength="50" type="textarea" rows="4"
						placeholder="请输入您的签名,最大长度为50"></el-input>
				</el-form-item>
				<el-form-item label-width="40">
					<div class="loadingBox">
						<el-progress :text-inside="true" striped :stroke-width="20" :percentage="percentage"
							:color="colors">
							<template #default="{ percentage }">
								<span style="color:aliceblue;">{{ getText(percentage) }}</span>
							</template>
						</el-progress>
					</div>
				</el-form-item>
				<el-form-item>
					<el-button color="#aaaaff" type="primary" @click="register()" plain>注册</el-button>
					<el-button color="#00aaff" type="primary" @click="router.push('/login')" plain> 去登录 </el-button>
				</el-form-item>

			</el-form>
		</div>
	</div>
</template>

<script setup>
import {
	reactive,
	ref,
	getCurrentInstance,
	watchEffect,
	onMounted,
} from 'vue';
import {
	ElMessageBox,
	ElNotification,
} from "element-plus";

import randomName from "@/plus/RandomName.js";


// 彩色进度条
const percentage = ref(0)
const colors = [
	{ color: '#d9534f', percentage: 21 },
	{ color: '#87cefa', percentage: 41 },
	{ color: '#f0ad4e', percentage: 61 },
	{ color: '#7b68ee', percentage: 81 },
	{ color: '#03c03c', percentage: 100 },
];

// 获取描述文本
let getText = (num) => {
	if (num >= 0 && num <= 20) {
		return "注册？";
	} else if (num > 20 && num <= 40) {
		return "注册！";
	} else if (num > 40 && num <= 60) {
		return "完成一半了！";
	} else if (num > 60 && num <= 80) {
		return "快完成了！";
	} else {
		return "谁准备好了！我准备好了！";
	}
}

// 导入路由对象
import {
	useRouter
} from "vue-router";

let router = useRouter();

// 引用表单实例，用于后续操作表单    
const ruleFormRef = ref(null);
// 导入vue实例对象
let {
	proxy
} = getCurrentInstance();

// 注册相关消息的表单
let registerForm = reactive({
	nickname: "", //用户昵称一般会给一个随机的用户值
	username: "", //账户密码是必填项，其他的值都是可以给随机值的
	password: "",
	passwordAg: "",
	avatarPath: "/headimg/default-1.jpeg",
	bio: "",
})


watchEffect(() => {
	// 计算已输入值的数量    
	let count = 0;
	if (registerForm.nickname) count++;
	if (registerForm.username) count++;
	if (registerForm.password) count++;
	if (registerForm.passwordAg) count++;
	if (registerForm.bio) count++;
	// 更新num变量    
	console.log(count * 20);
	percentage.value = count * 20;
});

// 获取随机的昵称文本
let getRandomName = () => {
	registerForm.nickname = randomName.getNickName();
}


// 自定义验证规则：检查两次输入的密码是否一致，并检查密码的复杂性    
const combinedValidate = (rule, value, callback) => {
	let error = null;

	if (value === '') {
		error = new Error('请再次输入密码');
	}

	// 首先验证两次输入的密码是否一致    
	if (value !== registerForm.password) {
		error = new Error('两次输入的密码不一致');
	}

	// 如果两次输入的密码一致，则继续验证密码的复杂性    
	if (!error && (!/[a-zA-Z]/.test(value) || !/\d/.test(value))) {
		error = new Error('密码至少需要包含字母和数字两种组合');
	}

	// 如果有错误，则返回错误信息    
	if (error) {
		callback(error);
	} else {
		callback();
	}
};

//账户名称重复验证方法
let Thread = null;
const repeatValidate = (rule, value, callback) => {
	if (Thread != null) {
		//清除计时器
		clearTimeout(Thread);
	}
	// 布置计时器
	Thread = setTimeout(() => {
		proxy.$axios.get("/users/getRepeatUsername", {
			params: {
				username: value
			}
		}).then((rls) => {
			if (rls.data == 'no') {
				callback('用户名已被占用')
			} else {
				callback();
			}
		}).catch((error) => {
			console.log(error);
		})
		Thread = null;
	}, 2000)
};



// 验证规则对象    
const rules = {
	nickname: [
		{ required: true, message: '昵称不能为空', trigger: 'blur' },
		{ min: 3, max: 10, message: '昵称长度在 3 到 10 个字符', trigger: 'blur' }
	],
	username: [
		{ required: true, message: '用户名不能为空', trigger: 'blur' },
		{ min: 6, max: 15, message: '用户名长度在 6 到 15 个字符', trigger: 'blur' },
		{ pattern: /^[A-Za-z0-9]+$/, message: '用户名只能包含字母和数字', trigger: 'blur' },
		{ validator: repeatValidate, trigger: 'change' }
	],
	password: [
		{ required: true, message: '密码不能为空', trigger: 'blur' },
		{ min: 8, max: 18, message: '密码长度在 8 到 18 个字符', trigger: 'blur' },
		// 使用自定义的验证规则    
		{ validator: combinedValidate, trigger: 'blur' }
	],
	passwordAg: [
		{ required: true, message: '密码不能为空', trigger: 'change' },
		{ min: 8, max: 12, message: '密码长度在 8 到 12 个字符', trigger: 'blur' },
		// 自定义验证规则，检查两次输入的密码是否相同    
		{ validator: combinedValidate, trigger: 'blur' }
	],
};


// 提交表单函数    
const register = () => {
	// 使用ruleFormRef.value来验证表单    
	ruleFormRef.value.validate((valid) => {
		if (valid) {
			proxy.$axios.post("/users/register", registerForm).then((rls) => {
				if (rls.data.result) {
					console.log("注册成功", rls);
					// 注册成功后，处理的行为
					// 1-直接跳转到功能页面
					// 2-跳转回登录页面，要求用户进行重新登录
					ElMessageBox.alert(`账户注册成功！`, `账户${registerForm.username}注册成功`, {
						confirmButtonText: '开始登录',
						draggable: true,
						callback: () => {
							// 跳转至登录页面
							router.push("/login");
						}
					})
				} else {
					// 输出注册失败的描述信息
					ElNotification({
						title: '警告',
						message: rls.data.describe,
						type: 'warning',
						offset: 100,
						duration: 30000,
					})
				}
			}).catch((error) => {
				ElNotification({
					title: '错误!',
					message: error,
					type: 'error',
					offset: 100,
					duration: 30000,
				})
			})
		} else {
			ElNotification({
				title: '表单中有错误项!',
				message: "请修改后重试！",
				type: 'error',
				offset: 100,
				duration: 30000,
			})
			return false;
		}
	});
};

</script>

<style scoped>
.loadingBox {
	width: 100%;
	height: 30px;
}

.register-background {
	width: 100vw;
	height: 100vh;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f0f2f5;

	/* 在这里加一个背景页面 */
}

.register-box {
	width: 500px;
	padding: 10px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	border-radius: 8px;
	background-color: #ffffff;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.register-form {
	width: 80%;
	/* display: flex;
	flex-direction: column;
	align-items: flex-start; */
}

.register-title {
	margin-bottom: 20px;
	text-align: center;
}
</style>